﻿using CodeGenerator.Common;
using CodeGenerator.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CodeGenerator.UI
{
    public partial class FrmCreateBuildHMulti : Form
    {
        public FrmCreateBuildHMulti()
        {
            InitializeComponent();

        }

        private List<TableInfo> selectTable = null;

        private string nameSpace = string.Empty;
        private string areaName = string.Empty;
        private string outputDir = string.Empty;
        private string prefix = string.Empty;

        private BackgroundWorker doWork = null;

        private void FrmCreateCodeMulti_Load(object sender, EventArgs e)
        {
            progressBar1.Visible = false;
            MainSetting info = Config.GetSetupInfo();
            txtNameSpace.Text = info.NameSpace;
            txtAreaName.Text = info.AreaName;
            txtPrefix.Text = info.Prefix;
            txtOutputDir.Text = info.OutputDir;
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.ShowDialog();
            txtOutputDir.Text = folderBrowserDialog.SelectedPath;
        }

        private void FrmCreateEntityMulti_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (doWork != null && doWork.IsBusy)
            {
                Common.MessageUtil.ShowWarning("任务执行中，无法关闭！！！");
                e.Cancel = true;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            selectTable = ucSelectTable1.GetSelectTable;

            if (selectTable.Count > 0)
            {
                outputDir = txtOutputDir.Text.Trim();

                if (string.IsNullOrEmpty(outputDir))
                {
                    Common.MessageUtil.ShowWarning("请选择输出路径！！！");
                    return;
                }

                nameSpace = txtNameSpace.Text.Trim();
                areaName = txtAreaName.Text.Trim();
                prefix = txtPrefix.Text.Trim();

                progressBar1.Visible = true;
                progressBar1.Minimum = 0;
                progressBar1.Maximum = selectTable.Count*9;
                doWork = new BackgroundWorker();
                doWork.DoWork += doWork_DoWork;
                doWork.ProgressChanged += doWork_ProgressChanged;
                doWork.RunWorkerCompleted += doWork_RunWorkerCompleted;
                doWork.WorkerReportsProgress = true;//此属性必须设置，否则读取不到进度
                doWork.WorkerSupportsCancellation = true; // 运行取消操作
                doWork.RunWorkerAsync();
            }
            else
            {
                Common.MessageUtil.ShowWarning("请至少选择一个表！！！");
            }
        }

        void doWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //如果用户取消了当前操作就关闭窗口。
            if (e.Cancelled)
            {
                this.lblMsg.Text = "用户取消操作！！！";
            }
            else
            {
                this.lblMsg.Text = "执行完成！！！";
                doWork.CancelAsync();
              
                System.Diagnostics.Process.Start(outputDir + "\\BuildH");
                this.Close();
            }

        }

        void doWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //修改进度条的显示。
            this.progressBar1.Value = e.ProgressPercentage;

            string message = e.UserState.ToString();
            this.lblMsg.Text = message;
        }

        void doWork_DoWork(object sender, DoWorkEventArgs e)
        {
            //在操作的过程中需要检查用户是否取消了当前的操作。
            if (doWork.CancellationPending == true)
            {
                e.Cancel = true;
                return;
            }

            BackgroundWorker bgWorker = sender as BackgroundWorker;

            ServerInfo serverInfo = Constant.CurrentServerInfo;
            serverInfo.DatabaseName = Constant.DatabaseName;
            IDatabase database = DBFactory.Database(serverInfo.DBType);

            string entityTempletePath = "\\Template\\BuildH\\Entity.cshtml";
            string bllTempletePath = "\\Template\\BuildH\\Bll.cshtml";
            string controllerTempletePath = "\\Template\\BuildH\\Controller.cshtml";
            string indexTempletePath = "\\Template\\BuildH\\Index.cshtml";
            string indexJsTempletePath = "\\Template\\BuildH\\IndexJs.cshtml";
            string formTempletePath = "\\Template\\BuildH\\Form.cshtml";
            string formJsTempletePath = "\\Template\\BuildH\\FormJs.cshtml";

            int i = 0;
            string dirPath = outputDir + "\\BuildH\\";
            foreach (var table in selectTable)
            {
                bgWorker.ReportProgress(i++, "正在生成生成【" + table.Name + "】表代码...");

                #region 生成BuildH代码模型
                BuildHCodeCreate model = new BuildHCodeCreate();

                // 表信息
                TableInfo tableInfo = new TableInfo();
                tableInfo.Name = table.Name;
                tableInfo.Comments = database.GetTableComments(serverInfo, Constant.DatabaseName, tableInfo.Name);
                tableInfo.ColumnList = database.GetColumnInfoList(serverInfo, serverInfo.DatabaseName, tableInfo.Name);

                model.TableInfo = tableInfo;

                // 基础配置信息
                model.Name = tableInfo.FilterName(prefix);  // 过滤掉前缀的表名
                model.NameSpace = nameSpace;
                model.AreaName = areaName;
                model.Refresh = true;
                model.Add = true;
                model.Edit = true;
                model.Delete = true;
                model.Detail = true;
                model.Close = true;
                model.BtnAuthorization = false;
                model.ViewAuthorization = true;

                // 列表模型
                List<CreateListCode> listCode = new List<CreateListCode>();
                foreach (var column in tableInfo.ColumnList)
                {
                    CreateListCode listModel = new CreateListCode();
                    listModel.No = column.Id;
                    listModel.Lable = column.Comments;
                    listModel.Field = column.Name;
                    listModel.Hidden = false;
                    listModel.Sortable = true;
                    listModel.Align = "left";
                    listModel.Width = 100;
                    listModel.Format = "字符串";
                    if (column.IsDateTime)
                    {
                        listModel.Format = "日期";
                    }
                    else if (column.IsBoolean)
                    {
                        listModel.Format = "布尔";
                    }
                    listModel.SortCode = Convert.ToInt32(column.Id);
                    listModel.Show = true;

                    listCode.Add(listModel);
                }

                model.ListCode = listCode;

                // 详细模型
                List<CreateFormCode> formCode = new List<CreateFormCode>();
                foreach (var column in tableInfo.ColumnList)
                {
                    CreateFormCode formModel = new CreateFormCode();
                    formModel.No = column.Id;
                    formModel.Lable = column.Comments;
                    formModel.Field = column.Name;
                    formModel.UIControlType = column.UIControlType;
                    if (column.UIControlType == ControlType.DateTime.ToString())
                    {
                        formModel.UIControlStyle = "form-control input-wdatepicker";
                    }
                    else if (column.UIControlType == ControlType.Select.ToString())
                    {
                        formModel.UIControlStyle = "ui-select";
                    }

                    else
                    {
                        formModel.UIControlStyle = "form-control";
                    }
                    formModel.UIControlValidator = "";

                    formModel.MaxLength = column.MaxLength;
                    formModel.ControlColspan = 12;
                    formModel.SortCode = Convert.ToInt32(column.Id);
                    formModel.Show = true;

                    formCode.Add(formModel);
                }
                model.FormCode = formCode;
                #endregion

                #region 生成代码
                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表实体类");
                string entityContent = RazorHelper.RunCompile(entityTempletePath, model);

                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表业务类");
                string bllContent = RazorHelper.RunCompile(bllTempletePath, model);

                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表控制器");
                string controllerContent = RazorHelper.RunCompile(controllerTempletePath, model);

                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表主页面");
                string indexContent = RazorHelper.RunCompile(indexTempletePath, model);

                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表主页面Js");
                string indexJsContent = RazorHelper.RunCompile(indexJsTempletePath, model);

                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表表单页面");
                string formContent = RazorHelper.RunCompile(formTempletePath, model);

                bgWorker.ReportProgress(i++, "正在生成【" + table.Name + "】表表单页面Js");
                string formJsContent = RazorHelper.RunCompile(formJsTempletePath, model);
                #endregion

                #region 创建代码文件
                bgWorker.ReportProgress(i++, "正在保存表【" + table.Name + "】代码");

                string entityPath = dirPath + "\\" + "\\Entity\\" + model.Name + "Entity.cs";
                string bllPath = dirPath + "\\" + "\\Bll\\" + model.Name + "Bll.cs";
                string controllerPath = dirPath +"\\" + "\\Controller\\" + model.Name + "Controller.cs";
                string indexPath = dirPath + "\\" + "\\Views\\" + model.Name + "\\Index.cshtml";
                string indexJsPath = dirPath + "\\" + "\\Js\\" + model.Name + "\\Index.js";
                string formPath = dirPath + "\\" + "\\Views\\" + model.Name + "\\Form.cshtml";
                string formJsPath = dirPath + "\\" + "\\Js\\" + model.Name + "\\Form.js";

                DirectoryUtil.Write(entityPath, entityContent);
                DirectoryUtil.Write(bllPath, bllContent);
                DirectoryUtil.Write(controllerPath, controllerContent);
                DirectoryUtil.Write(indexPath, indexContent);
                DirectoryUtil.Write(indexJsPath, indexJsContent);
                DirectoryUtil.Write(formPath, formContent);
                DirectoryUtil.Write(formJsPath, formJsContent);
                #endregion
            }

            System.Diagnostics.Process.Start(dirPath);
        }

    }
}
